<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-06-21 16:36:53
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-09-28 10:50:22
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\EquipManage\EquipType\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, unref, watch, reactive } from 'vue'
import { ElTree, ElInput, ElMessage } from 'element-plus'
import SCADAApi from '@/api/scada'
import { Dialog } from '@/components/Dialog'
import { Form } from '@/components/Form'
import { formschema, AddFormschema, AddDetectorFormschema, MarkerRules } from './MarkerSchema'
import { useForm } from '@/hooks/web/useForm'
import { BaseButton } from '@/components/Button'
import { useDictStore } from '@/store/modules/dictData'
import AddMarker from './AddMarker.vue'
import { useTable } from '@/hooks/web/useTable'
import { TableColumn } from '@/components/Table'
import { useRoute, useRouter } from 'vue-router'
import { useSCADAStore } from '@/store/modules/scada'
const deviceNo = ref<any>(useRoute().query.deviceNo)
const { push } = useRouter()
const DictStore = useDictStore()
const scadaStore = useSCADAStore()
DictStore.setDict('scada_device_type') //设备类型
const treeEl = ref<typeof ElTree>() //树结构
const currentNodeKey = ref<any>() //树结构ID
const departmentList = ref<any>([]) //树结构数据
const { t } = useI18n()
const ids = ref('')
const MarkerUuid = ref<string | undefined>('')
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const i = await SCADAApi.GetMarkerDetail(unref(MarkerUuid))
    i.detectorVos.map((item) => (item['deviceNo'] = i.deviceNo))
    currentRow.value = i
    return {
      list: i.detectorVos
    }
  },
  fetchDelApi: async () => {
    const res = await SCADAApi.DeleteDetector(unref(ids)[0])
    return !!res
  },
  immediate: false // 关闭初始化自动请求
})
const { loading, dataList } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const delLoading = ref(false)
const action = (data: any) => {
  push({
    path: '/SCADA/SetDetector',
    query: { detector: data.uuid, deviceNo: data.deviceNo }
  })
}
//删除附加设备
const delData = async (row: any | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.uuid] : elTableExpose?.getSelectionRows().map((v: any) => v.uuid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
//附加设备列表表格结构
const DetectorFormschema = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'devName',
    label: `设备名称`
  },
  {
    field: 'devNo',
    label: `设备序号`
  },
  {
    field: 'devType',
    label: `设备类型`,
    formatter: (_: Recordable, __: any, _cellValue: number) => {
      if (_cellValue == 0) {
        return t('流量计')
      } else {
        return t('变送器')
      }
    }
  },
  {
    field: 'model',
    label: `型号`
  },
  {
    field: 'action',
    label: '操作',
    slots: {
      default: (data: any) => {
        return (
          <>
            <span class="TableBtn" onClick={() => action(data.row)}>
              {t('详情')}
            </span>
            <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
              {t('删除')}
            </span>
          </>
        )
      }
    }
  }
])

const currentRow = ref()
const DetectorCurrent = ref()
const dialogTitle = ref('')
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
watch(
  () => currentRow.value,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)
const fetchDepartment = async () => {
  if (unref(deviceNo) && scadaStore.getMarkerList.length != 0) {
    //若是从附加设备页面跳转来
    const res = scadaStore.getMarkerList
    departmentList.value = res
    currentNodeKey.value = unref(deviceNo)
    MarkerUuid.value = res.filter((item: any) => {
      return item.deviceNo == unref(deviceNo)
    })[0]?.uuid
  } else {
    const res = await SCADAApi.GetMarkerList()
    scadaStore.setMarkerList(res)
    departmentList.value = res
    currentNodeKey.value = res[0].deviceNo //树结构ID也为第一个
    MarkerUuid.value = res[0].uuid
  }
  getList()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value) //应用到树结构
}
fetchDepartment() //获取树结构
const currentDepartment = ref('') //树结构搜索框内容
watch(
  () => currentDepartment.value, //监控树结构搜索框内容变化
  (val) => {
    unref(treeEl)!.filter(val)
  }
)
const currentChange = (data: any) => {
  MarkerUuid.value = data.uuid
  //树结构点击
  currentNodeKey.value = data.deviceNo
  getList()
}
const filterNode = (value: string, data: any) => {
  //树结构变化
  if (!value) return true
  return data.siteName.includes(value) || data.deviceNo.includes(value)
}
const dialogVisible = ref(false)
const saveLoading = ref(false)
const EditMarker = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const i = await SCADAApi.EditMarker(formData)
    if (i) {
      ElMessage.success('修改站点成功')
    } else {
      ElMessage.error('修改站点失败')
    }
  }
}
const actionType = ref('')
const MarkerAction = async (type: string) => {
  actionType.value = 'Marker'
  dialogTitle.value = '添加站点'
  if (type == 'edit') {
    EditMarker()
  } else if (type == 'delete') {
    const i = await SCADAApi.DeleteMarker(currentRow.value.uuid)
    if (i) {
      ElMessage.success('删除站点成功')
      fetchDepartment() //站点重新刷新
    } else {
      ElMessage.error('删除站点失败')
    }
  } else {
    dialogVisible.value = true
  }
}
const DetectorAction = async () => {
  actionType.value = 'Detector'
  dialogTitle.value = '添加附加设备'
  dialogVisible.value = true
  DetectorCurrent.value = {
    marUuid: currentRow.value.uuid,
    siteName: currentRow.value.siteName
  }
}
const writeRef = ref<ComponentRef<typeof AddMarker>>()
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    console.log(formData, actionType.value)
    if (actionType.value == 'Marker') {
      const res = await SCADAApi.AddMarker(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
      if (res) {
        dialogVisible.value = false
        ElMessage.success('添加站点成功')
        fetchDepartment() //获取树结构
      } else {
        ElMessage.error('添加站点失败')
      }
    } else {
      const res = await SCADAApi.AddDetector(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
      if (res) {
        dialogVisible.value = false
        ElMessage.success('添加附加设备成功')
        getList()
      } else {
        ElMessage.error('添加附加设备失败')
      }
    }
  }
}
</script>
<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px min-h-[580px]">
      <ElInput
        v-model="currentDepartment"
        class="flex-[2] mb-[10px]"
        :placeholder="t('搜索站点名称/编号')"
        clearable
      />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="deviceNo"
        :highlight-current="true"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'siteName'
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div :title="data.siteName" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.siteName }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <div class="flex-[3] ml-20px">
      <ContentWrap class="flex-[3] relative" id="marker" title="站点配置详情">
        <div class="absolute right-[30px] top-[10px]">
          <BaseButton size="small" type="primary" @click="MarkerAction('add')" class="AddbtnStyle">
            <Icon class="mr-[5px]" icon="ep:plus" :size="12" />新增
          </BaseButton>
          <BaseButton size="small" type="primary" @click="MarkerAction('edit')" class="AddbtnStyle">
            <Icon class="mr-[5px]" icon="ep:edit" :size="12" />修改
          </BaseButton>
          <BaseButton
            size="small"
            type="danger"
            @click="MarkerAction('delete')"
            class="AddbtnStyle"
          >
            <Icon class="mr-[5px]" icon="ep:delete" :size="12" />删除
          </BaseButton>
        </div>
        <Form
          labelPosition="top"
          :rules="MarkerRules"
          @register="formRegister"
          :schema="formschema"
        />
        <Dialog v-model="dialogVisible" :title="dialogTitle">
          <AddMarker
            v-if="actionType == 'Marker'"
            ref="writeRef"
            :form-schema="AddFormschema"
            :current-row="{}"
          />
          <AddMarker
            v-else
            ref="writeRef"
            :form-schema="AddDetectorFormschema"
            :current-row="DetectorCurrent"
          />
          <template #footer>
            <BaseButton type="primary" :loading="saveLoading" @click="save">
              {{ t('exampleDemo.save') }}
            </BaseButton>
            <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
          </template>
        </Dialog>
      </ContentWrap>
      <ContentWrap class="flex-[3] relative mt-20px" id="detector" title="附加设备列表">
        <div class="absolute right-[30px] top-[10px]">
          <BaseButton size="small" type="primary" @click="DetectorAction" class="AddbtnStyle">
            <Icon class="mr-[5px]" icon="ep:plus" :size="12" />新增
          </BaseButton>
        </div>
        <Table
          :columns="DetectorFormschema"
          :data="dataList"
          :loading="loading"
          sortable
          @register="tableRegister"
        />
      </ContentWrap>
    </div>
  </div>
</template>
<style scoped lang="less">
:deep(.el-col-4, .el-col-4.is-guttered),
:deep(.el-col-5, .el-col-5.is-guttered) {
  padding-right: 30px !important;
  //   position: relative;
  //   position: absolute;
}
:deep(.el-card__header) {
  padding: 15px !important;
}

:deep(.TableBtn) {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
